import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from '../../../widgets/one-operation/one-operation.component';
import {Router, ActivatedRoute} from '@angular/router';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {MsgConstants} from '../../../constants/constants';
import {TableUtil} from '../../../util/table-util';
import {MsgResult} from '../../../models/msg-result';
import {SiteDevicesService} from './site-devices.service';
import {SiteV2API} from '../site-v2-constants';



declare var $;
declare  var moment;

@Component({
  selector: 'app-site-devices',
  templateUrl: './site-devices.component.html',
  styleUrls: ['./site-devices.component.css']
})
export class SiteDevicesComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;


  proxy = {
    'siteDeviceAdd': () => this.siteDeviceAdd(),
    'siteDeviceUpdate': () => this.siteDeviceUpdate(),
    'siteDeviceDelete': () => this.siteDeviceDelete(),
    'siteDevicePollutant': () => this.siteDevicePollutant(),
    'siteDeviceAssign': () => this.siteDeviceAssign(),
  };

  siteMonitorId: Array<string> = [];

  snCodeArr: Array<string> = [];

  codMonitors;

  receiveTimeMonitorVal: string;

  receiveTimeStatusVal: string;

  table;

  startDate;
  endDate;
  monitorStartTime;
  monitorEndTime;
  statusStartTime;
  statusEndTime;


  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private siteDevicesService: SiteDevicesService,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject
  ) { }

  ngOnInit() {
    this.pushPage();
    this.loadSiteMonitor();
    this.initMonitorType();
  }

  ngAfterViewInit() {
    // 操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    const path = new Path('设备接入管理', null);
    this.pageSubject.pushPage('设备管理', '查询', path);
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 主题查询
   */
  loadSiteMonitor() {
    this.table = this.tableUtil.load('one_table_monitor', {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        {field: 'siteCode', title: '站点代码', align: 'left', visible: false, switchable: false},
        {field: 'siteName', title: '站点名称', align: 'left' , class: 'one-table-col-2',  formatter: this.siteNameFormatter},
        {field: 'snCode', title: '设备编号', align: 'left' , class: 'one-table-col-2'},
        {field: 'monitorName', title: '设备类型', align: 'left' , class: 'one-table-col-4'},
        {field: 'mPhone', title: '手机号', align: 'right', visible: false , class: 'one-table-col-2'},
        { field: 'ccid' , title: 'CCID', align: 'left'  , class: 'one-table-col-2'},
        {field: 'RECEIVETIME_MONITOR', title: '监测数据接收时间', align: 'left' , class: 'one-table-col-icon-6', sortName: 'RECEIVETIME_MONITOR',
          sortable: true, formatter: this.tableUtil.showToolTip},
        {field: 'RECEIVETIME_STATUS', title: '设备状态接收时间', align: 'left' , class: 'one-table-col-icon-6',
          sortName: 'RECEIVETIME_STATUS', sortable: true , formatter: this.tableUtil.showToolTip},
        {field: 'clientipinfClient', title: '客户端地址', align: 'left' , class: 'one-table-col-2'},
        {field: 'clientipinfServer', title: '服务端地址', align: 'left' , class: 'one-table-col-2', visible: false},
        {field: 'clientipinfTranster', title: '下发通讯地址', align: 'left' , class: 'one-table-col-2', visible: false},
        {field: 'statusUse', title: '使用状态', align: 'left' , class: 'one-table-col-2', formatter: this.statusUseFormat},
        {field: 'statusWork', title: '运行状态', align: 'left' , class: 'one-table-col-2', formatter: this.statusWorkFormat},
        // { field: 'remark',title:'说明' ,align:'left'},
        {field: 'transMode', title: '数据传输方式', align: 'left' , class: 'one-table-col-6', formatter: this.yesOrNoFormat},
        {field: 'createDate', title: '创建日期', align: 'left' , class: 'one-table-col-2', sortName: 'CREATE_DATE',
          sortable: true , visible: false},
        {field: 'updateDate', title: '修改日期', align: 'left' , class: 'one-table-col-2', visible: false,
          sortName: 'UPDATE_DATE', sortable: true },
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_site-monitor',
      url: SiteV2API.siteDevicePageListV2,
      method: 'post',
       // 传递附加参数
      queryParams: (params) => {
        params.siteName = $('#siteName').val();
        params.snCode = $('#snCode').val();
        params.monitorCode = $('#monitorCode').val();
        if (this.statusStartTime) {
          params.statusStartTime = moment(this.statusStartTime).format('YYYY-MM-DD');
        }
        if (this.statusEndTime) {
          params.statusEndTime = moment(this.statusEndTime).format('YYYY-MM-DD');
        }
        if (this.monitorStartTime) {
          params.monitorStartTime = moment(this.monitorStartTime).format('YYYY-MM-DD');
        }
        if (this.monitorEndTime) {
          params.monitorEndTime = moment(this.monitorEndTime).format('YYYY-MM-DD');
        }
        params.statusUse = $('#statusUse').val();
        params.statusWork = $('#statusWork').val();
        params.isAllocat = $('#isAllocat').val();
        return params;
      },
       // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
            value.updateDate = value.updateDate || '';
            value.RECEIVETIME_STATUS = value.receiveTimeStatus || '-';
            value.RECEIVETIME_MONITOR = value.receiveTimeMonitor || '-';
          });
        });
      },
      height: 700, // table高度
      sortable: true,
      sortOrder: 'desc',
      order: 'desc',
      sortName: 'CREATE_DATE',
      undefinedText: '-',
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      showExport: true,        // 是否显示导出按钮
      exportDataType: 'all',  // 导出类型
      buttonsAlign: 'right',   // 按钮位置
      exportTypes: ['excel'],   // 导出文件类型
      exportOptions: {
        ignoreColumn: [0],   // 根据索引忽[0,1,2]略某一列的导出数据
        fileName: '设备数据报表',   // 保存文件名称设置
        worksheetName: 'sheet1',   // 表格工作区名称
        tableName: '设备数据报表',
        excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
      },
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true // 响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private statusWorkFormat = (value, row, index) => {
    if (value === '1') {
      return '正常';
    }
    if (value === '2') {
      return '故障';
    }
    if (value === '3') {
      return '停用';
    }
  }
  private siteNameFormatter = (value, row, index) => {
    if (value) {
      return value;
    } else {
      return '<span class="text-red">未分配</span>';
    }
  };

  private statusUseFormat = (value, row, index) => {
    if (value ===  '0') {
      return '测试';
    }
    if (value ===  '1') {
      return '正式';
    }
  };

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat = (value, row, index) => {
    if (value ===  '1') {
      return 'gprs';
    }
    if (value ===  '2') {
      return 'lora';
    }
    if (value ===  '3') {
      return 'nb';
    }
  };
  /**
   * 初始化设备类型，下拉框
   */
  private initMonitorType() {
    this.siteDevicesService.getMonitor().subscribe(
      result => this.responseUtil.success(result , this.processMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processMonitorResult = (result: MsgResult) => {
    if (result && result.code ===  MsgConstants.MSG_CODE_OK) {
      this.codMonitors = result.data;
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化时间插件
   */
  initTimeControlConfig = () => {
    $('.ReceiveTime').daterangepicker({
      // timePickerIncrement: 5,
      singleDatePicker: false,
      timePicker24Hour: true,
      timePicker: true,
      timePickerSeconds: true,

      locale: {
        format: 'YYYY-MM-DD H:mm:ss',
        applyLabel: '确定',
        cancelLabel: '取消',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        firstDay: 1,
      },
       // 设置开始时间，可提前几天。
      startDate: moment().subtract(2, 'd').format('YYYY-MM-DD H:mm:ss'),

    });
  }

  /**
   * 选择时间后触发确认按钮获取时间
   * 点击取消按钮回复当前系统时间
   */
  receiveTimeApplyLabel() {
     // 绑定确认按钮
    $('#DataReceiveTimePoint').on('apply.daterangepicker', () => {
      this.receiveTimeMonitorVal = $('#DataReceiveTimePoint').val();
    });
     // 绑定取消按钮
    $('#DataReceiveTimePoint').on('cancel.daterangepicker', () => {
       // 回复当前系统时间
      this.initTimeControlConfig();
       // 把数据接收时间初始化为空；
      this.receiveTimeMonitorVal = '';
    });
    $('#DataReceiveTimePoint').val('');
  }

   // 选择时间后触发重新加载的方法,设备接收时间
  receiveTimeDevApplyLabel() {
    $('#DeviceReceiveTimePoint').on('apply.daterangepicker', () => {
      this.receiveTimeStatusVal =  $('#DeviceReceiveTimePoint').val();
    });
    $('#DeviceReceiveTimePoint').on('cancel.daterangepicker', () => {
      this.initTimeControlConfig();
      this.receiveTimeStatusVal = '';
    });
    $('#DeviceReceiveTimePoint').val('');
  }


  /**
   * 站点设备删除操作
   */
  private siteDeviceDelete() {
    const rows = this.table.bootstrapTable('getSelections');
    this.siteMonitorId = this.tableUtil.getCloumns(rows, 'id');
    if ( undefined ===  this.siteMonitorId || this.siteMonitorId.length ===  0 ) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', this.requestDelete);
    }
  }

  private requestDelete = () => {
    if (this.siteMonitorId.length ===  1) {
      this.siteDevicesService.siteMonitorDelete(this.siteMonitorId[0]).subscribe(
        result => this.responseUtil.success(result, this.processRoleDeleteResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.siteDevicesService.siteMonitorDeletes(this.siteMonitorId).subscribe(
        result => this.responseUtil.success(result, this.processRoleDeletesResult),
        message => this.responseUtil.error(message)
      );
    }
  };

  /**
   * 单一删除结果处理
   * @param result
   */
  processRoleDeleteResult = (result: MsgResult) => {
    if (result && result.code ===  MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 批量删除结果处理
   * @param result
   */
  processRoleDeletesResult = (result: MsgResult) => {
    if (result && result.code ===  MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 站点设备修改
   */
  private siteDeviceUpdate() {
    const rows = this.table.bootstrapTable('getSelections');
    this.siteMonitorId = this.tableUtil.getCloumns(rows, 'id');
    if (this.siteMonitorId.length !== 1) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.router.navigate(['update', {id: this.siteMonitorId[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 站点设备添加
   */
  private siteDeviceAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 设备权重
   */
  private siteDevicePollutant() {
    const rows = this.table.bootstrapTable('getSelections');
    this.snCodeArr = this.tableUtil.getCloumns(rows, 'snCode');
    if (this.snCodeArr.length !== 1) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.router.navigate(['pollutant', {snCode: this.snCodeArr[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 为设备分配站点
   */
  private siteDeviceAssign() {
    const rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo('请选择一条数据!');
    }
    const id = this.tableUtil.getCloumn(rows[0], 'id');
    // let snCode = this.tableUtil.getCloumn(rows[0], 'snCode');
    if (!!id) {
      this.router.navigate(['assign-site', {id: id}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo('请选择一条数据!');
    }
  }
  /**
   * 开始时间结束时间
   */
  startMonitorChange = () => {
    if (this.monitorStartTime > this.monitorEndTime) {
      this.monitorEndTime = null;
    }
  };
  endMonitorChange = () => {
    if (this.monitorStartTime > this.monitorEndTime) {
      this.monitorStartTime = null;
    }
  };
  disabledMonitorStartDate = (startValue) => {
    if (!startValue || !this.monitorEndTime) {
      return false;
    }
    return startValue.getTime() > this.monitorEndTime.getTime();
  };
  disabledMonitorEndDate = (endValue) => {
    if (!endValue || !this.monitorStartTime) {
      return false;
    }
    return endValue.getTime() < this.monitorStartTime.getTime();
  };
  /**
   * 开始时间结束时间
   */
  startStatusChange = () => {
    if (this.statusStartTime > this.statusEndTime) {
      this.statusEndTime = null;
    }
  };
  endStatusChange = () => {
    if (this.statusStartTime > this.statusEndTime) {
      this.statusStartTime = null;
    }
  };
  disabledStatusStartDate = (startValue) => {
    if (!startValue || !this.statusEndTime) {
      return false;
    }
    return startValue.getTime() > this.statusEndTime.getTime();
  };
  disabledStatusEndDate = (endValue) => {
    if (!endValue || !this.statusStartTime) {
      return false;
    }
    return endValue.getTime() < this.statusStartTime.getTime();
  };
}
